//
//  MessageController.swift
//  消息（会话）界面
//
//  Created by smile on 2019/7/23.
//  Copyright © 2019 ixuea. All rights reserved.
//

import UIKit

//导入发布订阅框架
import SwiftEventBus

class MessageController: BaseTitleController {
    
    /// 列表
    @IBOutlet weak var tableView: UITableView!
    
    /// 列表数据源
    var dataArray:[JMSGConversation] = []

    override func initViews() {
        super.initViews()
        setTitle("我的消息")
    }
    
    override func initDatas() {
        super.initDatas()
        
        //测试聊天SDK是否集成成功
//        JMSGConversation.createSingleConversation(withUsername: StringUtil.wrapperUserId("31")) { (conversation, error) in
//            if let conversation=conversation as? JMSGConversation{
//                //发送测试文本消息
//                conversation.sendTextMessage("我们是爱学啊，这是一条文本消息！")
//            }
//        }

    }

    func fetchData() {
        dataArray.removeAll()
        
        //获取所有会话
        JMSGConversation.allConversations { (datas, error) in
            if error==nil{
                if let conversations=datas as? [JMSGConversation] {
                    self.dataArray=conversations
                    self.tableView.reloadData()
                }
            }
        }
    }
    
    
    /// 视图已经显示了
    ///
    /// - Parameter animated: <#animated description#>
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        
        //获取数据
        fetchData()
        
        //监听消息未读数改变了
        SwiftEventBus.onMainThread(self, name: ON_MESSAGE_COUNT_CHANGED) { (render) in
            self.fetchData()
        }
    }
    
    /// 视图即将消失
    ///
    /// - Parameter animated: <#animated description#>
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        
        //移除监听
        SwiftEventBus.unregister(self, name: ON_MESSAGE_COUNT_CHANGED)
    }
    
    /// 启动方法
    ///
    /// - Parameter nav: <#nav description#>
    static func start(_ nav:UINavigationController) {
        //创建控制器
        let controller=nav.storyboard!.instantiateViewController(withIdentifier: "Message")
        
        //添加到导航控制器
        nav.pushViewController(controller, animated: true)
    }

}

// MARK: - 列表数据源和代理
extension MessageController:UITableViewDataSource,UITableViewDelegate{
    
    /// 返回有多少个
    ///
    /// - Parameters:
    ///   - tableView: <#tableView description#>
    ///   - section: <#section description#>
    /// - Returns: <#return value description#>
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return dataArray.count
    }
    
    /// 返回cell
    ///
    /// - Parameters:
    ///   - tableView: <#tableView description#>
    ///   - indexPath: <#indexPath description#>
    /// - Returns: <#return value description#>
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        //获取cell
        let cell=tableView.dequeueReusableCell(withIdentifier: CELL, for: indexPath) as! MessageCell
        
        //绑定数据
        cell.bindData(dataArray[indexPath.row])
        
        //返回cell
        return cell
    }
    
    /// cell点击
    ///
    /// - Parameters:
    ///   - tableView: <#tableView description#>
    ///   - indexPath: <#indexPath description#>
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        //获取数据
        let data=dataArray[indexPath.row]
        
        //获取对方用户
        let user=data.target as! JMSGUser
        
        ChatController.start(navigationController!, user.username)
    }
}
